package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.密码加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        log.info("加密后的密码为:{}", password);
        //2.根据用户名获取用户信息
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(employee.getUsername() != null, Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(wrapper);
        //3.判断用户是否存在
        if (one == null) {
            log.info("用户名不存在!");
            return R.error("用户名不存在!");
        }
        //4.判断密码是否一致
        if (!one.getPassword().equals(password)) {
            log.info("密码错误!");
            return R.error("密码错误!");
        }
        //5.判断权限,状态
        if (one.getStatus() == 0) {
            log.info("账户已被封禁!");
            return R.error("账户已被封禁!");
        }
        //6.登录成功 - 把用户id信息存入会话范围
        HttpSession session = request.getSession();
        session.setAttribute("employee", one.getId());
        //7.给出响应
        return R.success(one);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R loginout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功!");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R save(HttpServletRequest request,@RequestBody Employee employee) {
        log.info("新增员工->"+employee.toString());
        //设置初始密码 123456  md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        //设置创建时间 和 更新时间
       /* employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //设置创建人id 和 更新人id
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/

        boolean b = employeeService.save(employee);

        return b?R.success("成功"):R.error("失败");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        log.info("分页查询->page:"+page+" page:"+pageSize+" name:"+name);
        //设置分页
        Page pageInfo = new Page(page, pageSize);
        //设置查询条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Employee::getName,name);
        wrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询语句
        employeeService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改员工状态
     * @param employee
     * @return
     */
    @PutMapping
    public R update(HttpServletRequest request,@RequestBody Employee employee){
        log.error("线程id={}",Thread.currentThread().getId());
        log.info("修改:"+employee.toString());
        //获取修改人id
        /*Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());*/
        //执行语句
        boolean b = employeeService.updateById(employee);
        return b?R.success("成功"):R.error("失败");
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R updateById(@PathVariable Long id){
        log.info("id查询:"+id);
        Employee byId = employeeService.getById(id);
        if(byId!=null){
            return R.success(byId);
        }
        return R.error("失败");
    }

}
